package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.CsGameUnionmobile.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.LockKey;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActConstant;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.rank.RankReward;
import com.motu.monstercity.server.game.commondata.union.*;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import io.vertx.core.json.JsonArray;
import io.vertx.core.shareddata.Lock;
import org.bouncycastle.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 联盟总动员协议
 */
public class UnionmobileHandler {
    private static Logger logger = LoggerFactory.getLogger(UnionmobileHandler.class);
    // CMD_GAME_UNIONMOBILE_INFO = 73601; // 联盟总动员信息
    public static Object CMD_GAME_UNIONMOBILE_INFO(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        ErrorWord unlock = UnionMobileManager.isUnlock(userUnion,userInfo);
        if (unlock != null) {
            return unlock;
        }

        CSGameUnionmobileInfoResponse.Builder response = CSGameUnionmobileInfoResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        int serverGroup = ServerManager.getServerActGroup(userInfo.getServerId());
        // 获取玩家的专属任务列表
        UnionMobileInfo unionMobileInfo = UnionMobileManager.getUnionMobileInfo(userUnion.getUnionId());
        ProtoDataUtils.updatePBUserData(pbUserData, unionMobileInfo);
        UnionMobileManager.tryRefreshTask(userId,userUnion.getUnionId(),pbUserData);
        UserMobileInfo userMobileTaskInfo = UnionMobileManager.getUserMobileInfo(userInfo.getId());
        List<UnionMobileTaskInfo> unionMobileTaskList = UnionMobileManager.getUnionMobileTaskList(userUnion.getUnionId());
        List<UserMobileTaskInfo> userMobileTaskList = UnionMobileManager.getUserMobileTaskList(userInfo.getId());

        buildPb(pbUserData,userMobileTaskInfo,unionMobileTaskList,userMobileTaskList);
        return response;
    }


    // CMD_GAME_UNIONMOBILE_ACCEPT_TASK = 73604; // 联盟总动员接取任务
    public static Object CMD_GAME_UNIONMOBILE_ACCEPT_TASK(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        ErrorWord unlock = UnionMobileManager.isUnlock(userUnion,userInfo);
        if (unlock != null) {
            return unlock;
        }
        CSGameUnionmobileAcceptTaskRequest request = CSGameUnionmobileAcceptTaskRequest.parseFrom(clientParam.getData());
        int taskId = request.getTaskId();
        // 校验当前是否已经有接取任务了
        UserMobileInfo userMobileTaskInfo = UnionMobileManager.getUserMobileInfo(userInfo.getId());
        if (userMobileTaskInfo.getTaskId() != 0){   // 当前已经有任务了
            return ErrorWord.INVALID_OPERATION;
        }
        // 判断今日的接取次数是否已经达到最大了
        if(userMobileTaskInfo.isMaxAccept()){
            return ErrorWord.ALREADY_MAX;
        }
        // 获取任务配置
        UnionactionMain unionactionMain = UnionMobileManager.getUnionactionMain(taskId);
        if (unionactionMain == null) {
            return ErrorWord.BAD_PARAM;
        }

        CSGameUnionmobileAcceptTaskResponse.Builder response = CSGameUnionmobileAcceptTaskResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        long nextRefreshTime  = TimeUtils.getCurTime() + AllParam.UNIONMOBILE_TASK_TIME;
        int type = 0;
        UserMobileTaskInfo mobileTaskInfo = UnionMobileManager.getUserMobileTaskInfo(userId, taskId);
        if (mobileTaskInfo != null) {
            UnionactionTaskType unionactionTaskType = UnionMobileManager.getUnionactionTaskType(mobileTaskInfo.getTaskType());
            if (unionactionTaskType == null){
                return ErrorWord.NOT_DATA_1;
            }
            // 判断是否专属任务达到每日截取次数上限
            if(mobileTaskInfo.getTaskType() == UnionActionTaskConstant.TASK_TYPE_1){
                if (userMobileTaskInfo.isMaxComplete(unionactionTaskType.getNum())){
                    return ErrorWord.NOT_DATA_2;
                }
            }else if(mobileTaskInfo.getTaskType() == UnionActionTaskConstant.TASK_TYPE_2){
                if (userMobileTaskInfo.isMaxHighComplete(unionactionTaskType.getNum())){
                    return ErrorWord.NOT_DATA_3;
                }
            }else{
                return ErrorWord.NOT_DATA_4;
            }
            type = mobileTaskInfo.getTaskType();
            mobileTaskInfo.putRefreshTime(nextRefreshTime);
            mobileTaskInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData,mobileTaskInfo);
        }else{ // 如果是联盟任务
            UnionMobileTaskInfo unionMobileTask = null;
            Lock lock = null;
            try {
                lock = MainService.getVertLock(LockKey.getUnionMobileLock(userId));
                unionMobileTask = UnionMobileManager.getUnionMobileTaskInfo(userUnion.getUnionId(),taskId);
                if (unionMobileTask == null) return ErrorWord.NOT_DATA_1;
                if (unionMobileTask.getUserId() != 0){ return ErrorWord.WRONG_STATUS;}  // 已经被人接走了
                unionMobileTask.putUserId(userId);
                unionMobileTask.putRefreshTime(nextRefreshTime);
                unionMobileTask.update();
                ProtoDataUtils.updatePBUserData(pbUserData,unionMobileTask);
                BoardcastManager.publicUnionMobileTask(userInfo,userUnion.getUnionId(),unionMobileTask);   // 广播出去变化的信息
                type = UnionActionTaskConstant.TASK_TYPE_3;
            } catch (Exception e) {
                logger.info("联盟总动员接取公共任务,userId:{},taskId:{},error:{}", userId, taskId, e.getMessage());
            } finally {// 释放锁
                MainService.releaseVertLock(lock);
            }
            // 任务已经接取
            BoardcastManager.publicUnionMobileTask(userInfo, userUnion.getUnionId(), unionMobileTask);  // 同步其他盟友公共任务变化
        }
        userMobileTaskInfo.putTaskId(taskId);  // 设置当前任务Id
        userMobileTaskInfo.putTaskType(type);  // 设置任务类型
        userMobileTaskInfo.addTotalAcceptNum(1);  // 接取任务次数+1
        userMobileTaskInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData,userMobileTaskInfo);
        return response;
    }


    //  CMD_GAME_UNIONMOBILE_BUY_TIMES = 73605; // 联盟总动员购买接取任务次数
    public static Object CMD_GAME_UNIONMOBILE_BUY_TIMES(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        CSGameUnionmobileBuyTimesResponse.Builder response = CSGameUnionmobileBuyTimesResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        ErrorWord unlock = UnionMobileManager.isUnlock(userUnion,userInfo);
        if (unlock != null) {
            return unlock;
        }
        UserMobileInfo userMobileTaskInfo = UnionMobileManager.getUserMobileInfo(userInfo.getId());
        if (userMobileTaskInfo.isMaxBuy()){
            return ErrorWord.ALREADY_MAX;
        }
        //  获取消耗
        String[] split = Strings.split(AllParam.UNIONMOBILE_NEED, ';');
        if (split.length <= userMobileTaskInfo.getBuyNum()){
            return ErrorWord.BAD_PARAM;
        }
        String cost = split[userMobileTaskInfo.getBuyNum()];
        int costNum = Integer.parseInt(cost);
        // 检查是否足够
        if (costNum > 0){
            if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, costNum)) {
                return ErrorWord.ITEM_LACK;//钻石不足
            }
            RewardManager.subReward(userInfo, ItemId.DIAMOND, costNum, pbUserData,LogType.UNION_MOBILE_BUY_TASK_TIMES);
        }
        userMobileTaskInfo.addBuyNum(1);
        userMobileTaskInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData,userMobileTaskInfo);
        return response;
    }


    //  CMD_GAME_UNIONMOBILE_REFRESH_TASK = 73603; // 联盟总动员刷新公共任务
    public static Object CMD_GAME_UNIONMOBILE_REFRESH_TASK(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        CSGameUnionmobileRefreshTaskRequest request = CSGameUnionmobileRefreshTaskRequest.parseFrom(clientParam.getData());
        CSGameUnionmobileRefreshTaskResponse.Builder response = CSGameUnionmobileRefreshTaskResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        ErrorWord unlock = UnionMobileManager.isUnlock(userUnion,userInfo);
        if (unlock != null) {
            return unlock;
        }
        ErrorWord errorWord;
        if (request.getTaskType() != UnionActionTaskConstant.TASK_TYPE_3){  // 刷新专属任务
            errorWord = UnionMobileManager.refreshUserTask(userId, request.getTaskId(), pbUserData);
        }else{// 手动刷新公共任务
            errorWord = UnionMobileManager.refreshUnionTask(userId, request.getTaskId(),userUnion,pbUserData);
        }
        if (errorWord != null){
            return errorWord;
        }
        return response;
    }

    // CMD_GAME_UNIONMOBILE_MILEAGE_REWARD = 73606; // 联盟总动员領取里程獎勵
    public static Object CMD_GAME_UNIONMOBILE_MILEAGE_REWARD(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        CSGameUnionmobileMileageRewardResponse.Builder response = CSGameUnionmobileMileageRewardResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        ErrorWord unlock = UnionMobileManager.isUnlock(userUnion,userInfo);
        if (unlock != null) {
            return unlock;
        }
        String dateKey = String.valueOf(act.getId());
        UserMobileInfo userMobileInfo = UnionMobileManager.getUserMobileInfo(userId);
        // 获取积分情况
        int serverZoneId = ServerManager.getWarZoneId(userInfo.getServerId());
        long myUnionScore = RankManager.getMyScore(RankConstant.SERVER_UNION_RANK_MOBILE, serverZoneId, userUnion.getUnionId(), dateKey);
        long myScore = RankManager.getMyScore(RankConstant.SERVER_RANK_MOBILE, userInfo.getServerId(), userId, dateKey);
        JsonArray rewardInfoArray = userMobileInfo.getRewardInfoArray();
        JsonArray unionRewardArray = userMobileInfo.getUnionRewardInfoArray();
        CopyOnWriteArrayList<UnionactionReward> unionactionRewards = UnionMobileManager.getUnionactionRewards();
        List<RewardItem> rewards = new ArrayList<>();

        for (UnionactionReward reward : unionactionRewards) {
            // 1. 提前终止：已排序且当前分数不足
            if (reward.getUnionScore() > myUnionScore) {
                break;
            }

            // 2. 检查联盟奖励是否已领取
            boolean isUnionRewardNew = !unionRewardArray.contains(reward.getId());
            boolean isPerRewardNew = (myScore >= reward.getPerScore())
                    && !rewardInfoArray.contains(reward.getId());

            // 3. 处理新奖励
            if (isUnionRewardNew) {
                rewards.addAll(CommonUtils.takeReawrdItemFromStr(reward.getCommonReward()));
                unionRewardArray.add(reward.getId());
            }
            if (isPerRewardNew && myUnionScore >= reward.getUnionScore()) {
                rewards.addAll(CommonUtils.takeReawrdItemFromStr(reward.getExtraReward()));
                rewardInfoArray.add(reward.getId());
            }
        }

        // 4. 批量更新领取状态
        if (!rewards.isEmpty()) {
            userMobileInfo.putRewardInfo(rewardInfoArray.toString());
            userMobileInfo.putUnionRewardInfo(unionRewardArray.toString());
            userMobileInfo.update();

            RewardManager.addReward(userInfo, rewards, pbUserData, LogType.UNION_MOBILE_MILEAGE_REWARD);
            ProtoDataUtils.updatePBUserData(pbUserData, userMobileInfo);
        }
        return response;
    }


    //  CMD_GAME_UNIONMOBILE_GET_TASK_REWARD = 73608; // 联盟总动员获取任务奖励
    public static Object CMD_GAME_UNIONMOBILE_GET_TASK_REWARD(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        CSGameUnionmobileGetTaskRewardRequest request = CSGameUnionmobileGetTaskRewardRequest.parseFrom(clientParam.getData());
        int taskId = request.getTaskId();
        int taskType = request.getTaskType();
        CSGameUnionmobileGetTaskRewardResponse.Builder response = CSGameUnionmobileGetTaskRewardResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        ErrorWord unlock = UnionMobileManager.isUnlock(userUnion,userInfo);
        if (unlock != null) {
            return unlock;
        }
        UserMobileInfo userMobileInfo = UnionMobileManager.getUserMobileInfo(userId);
        if (userMobileInfo.getTaskId() != taskId && userMobileInfo.getTaskType() != taskType) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionactionMain unionactionMain = UnionMobileManager.getUnionactionMain(taskId);
        if (unionactionMain == null){
            return ErrorWord.NOT_DATA_9;
        }
        long score = unionactionMain.getScore();
        if (taskType == UnionActionTaskConstant.TASK_TYPE_3){
            // 如果完成的是联盟任务,等待自动刷新
            UnionMobileTaskInfo unionMobileTaskInfo = UnionMobileManager.getUnionMobileTaskInfo(userUnion.getUnionId(), taskId);
            if (unionMobileTaskInfo == null) {
                return ErrorWord.NOT_DATA_3;
            }
            if (!unionMobileTaskInfo.isComplete()) {  // 已经完成了 不变化
                return ErrorWord.NOT_DATA_4;
            }
            unionMobileTaskInfo.putIsComplete(UnionActionTaskConstant.TASK_GET_REWARD);  // 设置已领取状态
            unionMobileTaskInfo.putRefreshTime(0);
            unionMobileTaskInfo.update();
            BoardcastManager.publicUnionMobileTask(userInfo, userUnion.getUnionId(), unionMobileTaskInfo);  // 同步其他盟友公共任务变化
            ProtoDataUtils.updatePBUserData(pbUserData, unionMobileTaskInfo, true);
        }else{
            UserMobileTaskInfo mobileTaskInfo = UnionMobileManager.getUserMobileTaskInfo(userId, taskId);
            if (mobileTaskInfo == null) {
                return ErrorWord.NOT_DATA_5;
            }
            if (!mobileTaskInfo.isComplete()) {
                return ErrorWord.NOT_DATA_6;
            }
            // 完成后刷新时间为二小时
            int completeTime = AllParam.UNIONMOBILE_COMPLETE_TIME * TimeUtils.MINUTE;
            mobileTaskInfo.putRefreshTime(TimeUtils.getCurTime() + completeTime);  // 设置下次刷新时间
            mobileTaskInfo.putIsComplete(UnionActionTaskConstant.TASK_GET_REWARD);
            UnionactionTaskType unionactionTaskType = UnionMobileManager.getUnionactionTaskType(mobileTaskInfo.getTaskType());
            if (unionactionTaskType != null) {
                score += unionactionTaskType.getScoreBonus() * score / 10000;  // 百分比加成
            }

            mobileTaskInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, mobileTaskInfo, true);
        }
        // 完成任务更新主体信息
        userMobileInfo.addScore(score);
        userMobileInfo.resetCurTask();
        ProtoDataUtils.updatePBUserData(pbUserData, userMobileInfo, true);
        //  获取配置的积分然后加入排行榜
        UnionMobileManager.updateUnionMobileUserRank(act, userInfo, userUnion.getUnionId(), score);  // 更新个人排行榜



        String dateKey = String.valueOf(act.getId());
        // 获取积分情况
        int serverZoneId = ServerManager.getWarZoneId(userInfo.getServerId());
        long myUnionScore = RankManager.getMyScore(RankConstant.SERVER_UNION_RANK_MOBILE, serverZoneId, userUnion.getUnionId(), dateKey);
        long myScore = RankManager.getMyScore(RankConstant.SERVER_RANK_MOBILE, userInfo.getServerId(), userId, dateKey);
        response.setMyScore(myScore);
        response.setUnionScore(myUnionScore);
        return response;
    }


    // CMD_GAME_UNIONMOBILE_RANK_INFO = 73607; // 排行榜信息
    public static Object CMD_GAME_UNIONMOBILE_RANK_INFO(RequestParam clientParam) throws Exception {
        CSGameUnionmobileRankInfoRequest request = CSGameUnionmobileRankInfoRequest.parseFrom(clientParam.getData());
        CSGameUnionmobileRankInfoResponse.Builder response = CSGameUnionmobileRankInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        long actId = act.getId();
        int serverId = userInfo.getServerId();
        String dateKey = String.valueOf(actId);
        int type = request.getType();
        int rankType;
        int num;
        if (type == 1) {
            rankType = RankConstant.SERVER_RANK_MOBILE;
            num = AllParam.UNIONMOBILE_RANK_MEMBER_LIST_MAX;
        } else if (type == 2) {
            rankType = RankConstant.SERVER_UNION_RANK_MOBILE;
            serverId = ServerManager.getWarZoneId(serverId);
            num = AllParam.UNIONMOBILE_RANK_UNION_LIST_MAX;
        } else {
            return ErrorWord.BAD_PARAM;
        }

        Common.PBRankInfo.Builder pbRankInfo = Common.PBRankInfo.newBuilder();
        List<Common.PBRankMember.Builder> memberList = RankManager.getRankMemberList(rankType, serverId, dateKey, num);
        for (Common.PBRankMember.Builder pbRankMember : memberList) {
            pbRankInfo.addMembers(pbRankMember.build());
        }

        int myRank = RankManager.getMyRank(rankType, serverId, userId, dateKey);
        pbRankInfo.setMyRank(myRank);
        long myScore = RankManager.getMyScore(rankType, serverId, userId, dateKey);
        pbRankInfo.setMyScore(myScore);
        response.setType(type);
        response.setPbRankInfo(pbRankInfo.build());

        return response;
    }



    // CMD_GAME_UNIONMOBILE_RANK_REWARD = 73602; // 联盟总动员領取排行榜獎勵
    public static Object CMD_GAME_UNIONMOBILE_RANK_REWARD(RequestParam clientParam) throws Exception {
        CSGameUnionmobileRankRewardRequest request = CSGameUnionmobileRankRewardRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isStart()) {// 活动期间
            return ErrorWord.NOT_DATA; // 活动未开始
        }

        if (!UnionMobileManager.isRewardTime(act)) {
            return ErrorWord.WRONG_STATUS; // 活动未开始
        }
        int rankId = request.getRankType();
        int myRank = 0;
        UserMobileInfo userMobileInfo = UnionMobileManager.getUserMobileInfo(userId);
        int serverGroup = ServerManager.getServerActGroup(userInfo.getServerId());
        // 判断要领取的是哪个排行榜
        String dataKey = String.valueOf(act.getId());
        if (rankId == RankConstant.SERVER_RANK_MOBILE) {
            if (userMobileInfo.getSingleRankReward() > 0) {
                return ErrorWord.ALREADY_MAX;
            }
            myRank = RankManager.getMyRank(rankId, serverGroup, userId, dataKey);
        } else if (rankId == RankConstant.SERVER_UNION_RANK_MOBILE) {
            if (userMobileInfo.getUnionRankReward() > 0) {
                return ErrorWord.ALREADY_MAX;
            }
            myRank = RankManager.getMyRank(rankId, serverGroup, userUnion.getUnionId(), dataKey);
        } else {
            return ErrorWord.BAD_PARAM;
        }

        if (myRank <= 0) {
            return ErrorWord.NOT_DATA_3; // 未上榜
        }
        // 根据排行榜类型查出名次并下发奖励
        RankReward rankReward = RankManager.getRankReward(rankId, myRank);
        if (rankReward == null) {
            return ErrorWord.NOT_DATA;
        }
        CSGameUnionmobileRankRewardResponse.Builder response = CSGameUnionmobileRankRewardResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, rankReward.getReward(), pbUserData, LogType.UNION_MOBILE_RANK_REWARD, rankId, myRank);
        // 将领奖标记存起来
        if (rankId == RankConstant.SERVER_RANK_MOBILE) {
            userMobileInfo.putSingleRankReward(rankReward.getId());
        } else {
            userMobileInfo.putUnionRankReward(rankReward.getId());
        }
        userMobileInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userMobileInfo);
        return response;
    }

    // 封装pb
    public static void buildPb(Common.PBUserData.Builder pbUserData,UserMobileInfo userMobileTaskInfo, List<UnionMobileTaskInfo> mobileTaskInfos, List<UserMobileTaskInfo>  userMobileTaskInfos) {
          if (userMobileTaskInfo != null){
              ProtoDataUtils.updatePBUserData(pbUserData, userMobileTaskInfo, true);
          }
          if (mobileTaskInfos != null && !mobileTaskInfos.isEmpty()) {
              for (UnionMobileTaskInfo mobileTaskInfo:mobileTaskInfos){
                  ProtoDataUtils.updatePBUserData(pbUserData, mobileTaskInfo, true);
              }
          }
        if (userMobileTaskInfos != null && !userMobileTaskInfos.isEmpty()) {
            for (UserMobileTaskInfo userMobileTaskInfo1:userMobileTaskInfos){
                ProtoDataUtils.updatePBUserData(pbUserData, userMobileTaskInfo1, true);
            }
        }
    }


}
